import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { customerNotes } from '@/lib/schema';
import { eq } from 'drizzle-orm';

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const notes = await db
      .select()
      .from(customerNotes)
      .where(eq(customerNotes.customerId, parseInt(params.id)))
      .orderBy(customerNotes.createdAt);

    return NextResponse.json(notes);
  } catch (error) {
    console.error('获取客户备注失败:', error);
    return NextResponse.json(
      { error: '获取客户备注失败' },
      { status: 500 }
    );
  }
}

export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const body = await request.json();
    
    const [newNote] = await db
      .insert(customerNotes)
      .values({
        customerId: parseInt(params.id),
        content: body.content,
        type: body.type || 'general',
        createdBy: body.createdBy || 'admin'
      })
      .returning();

    return NextResponse.json(newNote, { status: 201 });
  } catch (error: any) {
    console.error('创建客户备注失败:', error);
    return NextResponse.json(
      { error: '创建客户备注失败: ' + (error.message || '数据库错误') },
      { status: 500 }
    );
  }
}